const express = require('express');
const path = require('path');
const app = express();
const port = 30000;
require('dotenv').config();

const LoginRouter = require('./src/routes/Login');
const UserDataRouter = require('./src/routes/UserData');
const FileUpload = require('./src/routes/FileUpload');
const WebSocket = require('./src/webSocket/Server');
const System = require('./src/routes/System');
const db = require('./src/database/db');

app.use((req, res, next) => {
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE');
    res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
    next();
});

const AvatarDir = path.join(__dirname, './Data/Avatar');
app.use('/Avatar', express.static(AvatarDir));

app.use('/Login', LoginRouter);
app.use('/UserData', UserDataRouter);
app.use('/FileUpload', FileUpload);
app.use('/System', System);

app.get('/', (req, res) => {
    res.send('Hello World!');
});

app.get('/niubi', (req, res) => {
    res.send('你很牛逼');
});

const server = app.listen(port, () => {
    console.log(`Server is running on http://localhost:${port}`);
});

// 捕获未处理的 Promise 拒绝
process.on('unhandledRejection', (reason, promise) => {
    console.error('Unhandled Rejection at:', promise, 'reason:', reason);
});

// 捕获未捕获的异常
process.on('uncaughtException', (err) => {
    console.error('Uncaught Exception:', err);
    // 优雅地关闭服务器和数据库连接
    closeResources();
});

// 监听 SIGTERM 信号，用于优雅关闭服务器
process.on('SIGTERM', () => {
    console.log('SIGTERM signal received: closing HTTP server');
    closeResources();
});

// 监听 SIGINT 信号，用于优雅关闭服务器（例如 Ctrl+C）
process.on('SIGINT', () => {
    console.log('SIGINT signal received: closing HTTP server');
    closeResources();
});

// 关闭所有资源的函数
function closeResources() {
    server.close(() => {
        console.log('HTTP server closed');
        WebSocket.close();
        db.end((err) => {
            if (err) {
                console.error('Error closing database connection:', err);
            } else {
                console.log('Database connection closed');
            }
            process.exit(0);
        });
    });
}
